//
//  MyOrderViewController.m
//  HongFuShop
//
//  Created by chirui on 2017/8/15.
//  Copyright © 2017年 Shui. All rights reserved.
//

#import "MyOrderViewController.h"
#import "MyOrderTableViewCell.h"
#import "OrderDetailsViewController.h"

@interface MyOrderViewController ()<HTHorizontalSelectionListDataSource,HTHorizontalSelectionListDelegate,UIScrollViewDelegate,UITableViewDataSource,UITableViewDelegate,UIAlertViewDelegate,UITextFieldDelegate>
{
    
    //创建的ui
    UIScrollView * _topScrollView;
    UIScrollView * _scrollView;//内容上的滑块
    NSArray * _titileArray;
    UITableView * _tableView;
    CGPoint _point; //设置偏移量时使用
    
    NSMutableArray * _dataArray;
    NSString * type;
    int _page;
    int _totailPage;
    
    UIView * noBodyView;
}

@property(nonatomic,strong)HTHorizontalSelectionList * selectionList;

@end

@implementation MyOrderViewController

-(void)viewWillAppear:(BOOL)animated {

    if ([self.getGoods isEqualToString:@"getGoods"]) {
        
        _selectionList.selectedButtonIndex = 2;
         type = @"deliver";
        
    }else {
    
         type = @"all";
    }

}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    if ([self.getGoods isEqualToString:@"getGoods"]) {
        
        _selectionList.selectedButtonIndex = 2;
        type = @"deliver";
        
    }else {
        
        type = @"all";
    }

    TitleView(@"我的订单");
    _dataArray = @[].mutableCopy;
    _titileArray =@[@"全部订单",@"待发货",@"待收货",@"已完成"];
   
    _page = 1;
    [self creatUI];
    [self getMyOrderListData];
    
    noBodyView = [NothingMessageView creatNothingMessageViewFrame:CGRectMake(WIDTH/2-100, (HEIGHT-64)/2-100, 200, 200) andMessageStr:@"您还没有此类订单哦~" onView:nil];
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithIcon:@"icon_public_return" target:self action:@selector(back)];
    
}

-(void)back{
    
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)creatUI{
    //标题的ScrollView
    
    self.edgesForExtendedLayout =UIRectEdgeNone;
    
    _selectionList =[[HTHorizontalSelectionList alloc]initWithFrame:CGRectMake(0, 0, WIDTH, 50)];
    _selectionList.dataSource=self;
    _selectionList.delegate=self;
    [self.view addSubview:_selectionList];
    [_selectionList setTitleFont:[UIFont systemFontOfSize:17] forState:UIControlStateSelected];
    [_selectionList setTitleFont:[UIFont systemFontOfSize:16] forState:UIControlStateNormal];
    [_selectionList setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [_selectionList setTitleColor:NavBackColor forState:UIControlStateSelected];
    //设置button之间的间距
    float WidthBtnFloat;
    if (ISP4||ISP5) {
        WidthBtnFloat =8;
    }else if (ISP6){
        WidthBtnFloat =10;
    }else {
        WidthBtnFloat =15;
    }
    UIView * line =[[UIView alloc]initWithFrame:CGRectMake(0, 49, WIDTH, 1)];
    line.backgroundColor =Color(248, 248, 248);
    [_selectionList addSubview:line];
    _selectionList.buttonInsets= UIEdgeInsetsMake(5,WidthBtnFloat, 5, WidthBtnFloat);
    //滑动按钮下边的滑块设置
    _selectionList.selectionIndicatorColor = NavBackColor;
    _selectionList.selectionIndicatorHeight =3;
    _selectionList.bottomTrimColor =[UIColor whiteColor];
    
  
   
    
    _tableView =[[UITableView alloc]initWithFrame:CGRectMake( 0, 50,WIDTH, HEIGHT-64-50) style:UITableViewStyleGrouped];
    _tableView.delegate=self;
    _tableView.dataSource=self;
    [self.view addSubview:_tableView];
    
    [_tableView registerNib:[UINib nibWithNibName:[MyOrderTableViewCell reuseIdentifier] bundle:nil] forCellReuseIdentifier:[MyOrderTableViewCell reuseIdentifier]];
    
    MJRefreshNormalHeader * header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        _page =1;
        [self getMyOrderListData];
        
    }];
    _tableView.mj_header =header;
    MJRefreshAutoNormalFooter *  footer =[MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        _page++;
        [self getMyOrderListData];
    }];
    
    footer.automaticallyRefresh = YES;
    _tableView.mj_footer =footer;
    _tableView.mj_footer.hidden = NO;
    
}

#pragma mark------HTHorizontalSelectionListDelegate实现--
//点击效果
-(void)selectionList:(HTHorizontalSelectionList *)selectionList didSelectButtonWithIndex:(NSInteger)index{
    
    //    typeStr = [NSString stringWithFormat:@"%ld",index];
    //    NSLog(@"typeStr === %@",typeStr);
    _page =1;
    
    switch (index) {
        case 0:
            type = @"all";  //全部订单
            [self getMyOrderListData];
            break;
        case 1:
            type = @"create";  //待发货
            [self getMyOrderListData];
            break;
        case 2:
            type = @"deliver";  //待收货
            [self getMyOrderListData];
            break;
        case 3:
            type = @"done";  //已完成
            [self getMyOrderListData];
            break;
        default:
            break;
    }

    [UIView animateWithDuration:0.6 animations:^{
        
        _scrollView.contentOffset =CGPointMake(WIDTH * index, 0);
    }];
    UITableView *tableViwe=(id)[self.view viewWithTag:1000+index];
    [tableViwe reloadData];
    
}
//返回下表对应的文字按钮
-(NSString *)selectionList:(HTHorizontalSelectionList *)selectionList titleForItemWithIndex:(NSInteger)index{
    
    return _titileArray[index];
}
//多少个
-(NSInteger)numberOfItemsInSelectionList:(HTHorizontalSelectionList *)selectionList{
    
    return _titileArray.count;
    
}

#pragma mark------tableViewdelegate----

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
   
    return _dataArray.count;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    NSDictionary * dic = _dataArray[section];
    NSArray * array =  dic[@"order_goods"];
    return array.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    return 120;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NSDictionary * dic = _dataArray[indexPath.section][@"order_goods"][indexPath.row];
    MyOrderTableViewCell  * cell = [tableView dequeueReusableCellWithIdentifier:[MyOrderTableViewCell reuseIdentifier] forIndexPath:indexPath];
    
    cell.goodsName.frame = CGRectMake(117, 11, WIDTH - 127, 20);
    cell.goodsName.text =  [NSString stringWithFormat:@"%@", dic[@"goods_name"]];
    cell.goodsName.numberOfLines = 2;
    
    [cell.goodsImge sd_setImageWithURL:ImageUrl(dic[@"src"]) placeholderImage:ImageName(@"img_new_default")];
     cell.goodsNumber.text = [NSString stringWithFormat:@"x%@",dic[@"count"]];
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    NSLog(@"dic == %@",dic);
    
    return cell;
    
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 70;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    
    return 50;
    
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    //    HealthDetailsViewController * health =[[HealthDetailsViewController alloc]init];
    //    health.hidesBottomBarWhenPushed = YES;
    //    [self.navigationController pushViewController:health animated:YES];
    
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    NSDictionary * dic = _dataArray[section];
    UIView * heardView =[[UIView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, 70)];
    heardView.backgroundColor =[UIColor groupTableViewBackgroundColor];
    
    UIView * view =[[UIView alloc]initWithFrame:CGRectMake(0, 10, WIDTH, 60)];
    view.backgroundColor =[UIColor whiteColor];
    
    [heardView addSubview:view];
    
    UILabel * typeLabel =[[UILabel alloc]initWithFrame:CGRectMake(10, 10, WIDTH-90, 20)];
    typeLabel.font =[UIFont systemFontOfSize:15];
    typeLabel.textColor = [UIColor blackColor];
    typeLabel.text = [NSString stringWithFormat:@"订单编号：%@",dic[@"order_sn"]];
    [view addSubview:typeLabel];
    
    UILabel * timeLabel =[[UILabel alloc]initWithFrame:CGRectMake(10, 35, WIDTH-90, 20)];
    timeLabel.font =[UIFont systemFontOfSize:15];
    timeLabel.textColor = [UIColor blackColor];
    timeLabel.text = [NSString stringWithFormat:@"下单时间：%@",dic[@"order_time"]];
    [view addSubview:timeLabel];
    
    
    UILabel * stasLabel =[[UILabel alloc]initWithFrame:CGRectMake(WIDTH- 80, 20, 80, 20)];
    stasLabel.textAlignment = NSTextAlignmentCenter;
    stasLabel.font =[UIFont systemFontOfSize:15];
    stasLabel.textColor = [UIColor redColor];
    stasLabel.text = dic[@"order_status_dict"];
    [view addSubview:stasLabel];
    
    return heardView;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    
    UIView * footerView =[[UIView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, 50)];
    footerView.backgroundColor =[UIColor whiteColor];
    
    NSDictionary * dic = _dataArray[section];
    NSString * statisStr = dic[@"order_status"];
    if ([statisStr isEqualToString:@"create"]) {
        [self creatBoardBtnFrame:CGRectMake(WIDTH-160,10, 70, 30) andTitleSte:@"查看订单" andSEL:@selector(lookMessageBtn:) andBtnTag:section onView:footerView];
        
        [self creatBoardBtnFrame:CGRectMake(WIDTH-80,10, 70, 30) andTitleSte:@"取消订单" andSEL:@selector(cannleOrderBtn:) andBtnTag:section onView:footerView];
        
    
    }
    // 待收货
    if ([statisStr isEqualToString:@"deliver"]) {
        [self creatBoardBtnFrame:CGRectMake(WIDTH-160,10, 70, 30) andTitleSte:@"查看订单" andSEL:@selector(lookMessageBtn:) andBtnTag:section onView:footerView];
          [self creatBoardBtnFrame:CGRectMake(WIDTH-80,10, 70, 30) andTitleSte:@"确认收货" andSEL:@selector(markSureOrderBtn:) andBtnTag:section onView:footerView];
    }
    // 已完成
    if ([statisStr isEqualToString:@"done"]) {
        [self creatBoardBtnFrame:CGRectMake(WIDTH-160,10, 70, 30) andTitleSte:@"查看订单" andSEL:@selector(lookMessageBtn:) andBtnTag:section onView:footerView];
        [self creatBoardBtnFrame:CGRectMake(WIDTH-80,10, 70, 30) andTitleSte:@"删除订单" andSEL:@selector(deledateOrderBtn:) andBtnTag:section onView:footerView];
        
    }
    
    return footerView;
}

-(void)markSureOrderBtn:(UIButton *)btn {

    NSDictionary * dic = _dataArray[btn.tag];
    [self markSureOrderRequestFor:dic[@"order_id"]];
    NSLog(@"cannel...");
}

-(void)cannleOrderBtn:(UIButton *)btn {
    
    NSDictionary * dic = _dataArray[btn.tag];
    [self cannelOrderRequestFor:dic[@"order_id"]];
    NSLog(@"cannel...");
}

-(void)deledateOrderBtn:(UIButton *)btn {
    
    NSDictionary * dic = _dataArray[btn.tag];
    [self deledateOrderRequestFor:dic[@"order_id"]];
    NSLog(@"deledate...");
}

-(void)lookMessageBtn:(UIButton *)btn {
    
    NSDictionary * dic = _dataArray[btn.tag];
    [self getOrderDetailsRequestFor:dic[@"order_id"]];

}

#pragma mark 网络接口

// cannel_order
-(void)cannelOrderRequestFor:(NSString *)orderId {
    
    NSDictionary * dic = @{@"user_id":USER_DEFAULTGet(@"user_id"),
                           @"token":USER_DEFAULTGet(@"token"),
                           @"order_id":orderId};
    
    SHuiMBhubNoTimeLoding;
    [PostNetWorking postNetWorkingStr:RequestUrlStr(cancel_order_api) andparameters:dic Success:^(id responseObject) {
        SHuiMBHidleYes;
        if (codeSucess) {
            SHuiMBhudTextTimeStr(@"取消订单成功");
            
            _page = 1;
            
            [self getMyOrderListData];
        }else {
            
            SHuiMBhudTextTimeStr(responseObject[@"mark"]);
            
        }
        
    } failed:^(NSError *error) {
        SHuiMBHidleYes;
        SHuiMBhudTextNetError;
    }];
    
}

-(void)markSureOrderRequestFor:(NSString *)orderId {
    
    NSDictionary * dic = @{@"user_id":USER_DEFAULTGet(@"user_id"),
                           @"token":USER_DEFAULTGet(@"token"),
                           @"order_id":orderId};
    
    SHuiMBhubNoTimeLoding;
    [PostNetWorking postNetWorkingStr:RequestUrlStr(markSure_order_api) andparameters:dic Success:^(id responseObject) {
        SHuiMBHidleYes;
        if (codeSucess) {
            SHuiMBhudTextTimeStr(@"收货成功");
            
            _page = 1;
            
            [self getMyOrderListData];
        }else {
            
            SHuiMBhudTextTimeStr(responseObject[@"mark"]);
            
        }
        
    } failed:^(NSError *error) {
        SHuiMBHidleYes;
        SHuiMBhudTextNetError;
    }];
    
}



-(void)getMyOrderListData{
    
    
    if (_totailPage != 0) {
        if(_page == _totailPage + 1){
            [_tableView.mj_footer setState: MJRefreshStateNoMoreData];
            
            return ;
        }
    }
    NSDictionary * dic = @{@"order_status":type,
                           @"page":[NSString stringWithFormat:@"%d",_page],
                           @"page_num":@"10",
                           @"user_id":USER_DEFAULTGet(@"user_id"),
                           @"token":USER_DEFAULTGet(@"token")
                           };
    
    //    SHuiMBhubNoTimeStr(@"正在加载...");
    [PostNetWorking postNetWorkingStr:RequestUrlStr(get_orderList_api) andparameters:dic Success:^(id responseObject) {
        SHuiMBHidleYes;
        if (codeSucess) {
            _totailPage = [SHJudgeTools totailpageNumberForTotailNumber:responseObject[@"datas"][@"total_count"]];
            if (_page==1) {
                
                if (_dataArray) {
                    
                    [_dataArray removeAllObjects];
                }
                if ([responseObject[@"datas"][@"list"]  isKindOfClass:[NSArray class]]) {
                    
                    for (NSDictionary * dic in responseObject[@"datas"][@"list"]) {
                        
                        [_dataArray addObject:dic];
                    }
                }
            }else {
                
                if ([responseObject[@"datas"][@"list"]  isKindOfClass:[NSArray class]]) {
                    
                    for (NSDictionary * dic in responseObject[@"datas"][@"list"]) {
                        
                        [_dataArray addObject:dic];
                    }
                }
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                
                
                if (_dataArray.count>0) {
                    noBodyView.hidden =YES;
                    if (_dataArray.count<10) {
                        
                        _tableView.mj_footer.hidden = YES;
                    }else {
                        _tableView.mj_footer.hidden = NO;
                    }
                }else {
                    _tableView.mj_footer.hidden = YES;
                    noBodyView.hidden =NO;
                    
                    [self.view addSubview:noBodyView];
                }
                [_tableView.mj_header endRefreshing];
                [_tableView.mj_footer endRefreshing];
                [_tableView reloadData];
                
            });
            
        }else {
            
            SHuiMBhudTextTimeStr(responseObject[@"mark"]);
        }
        
    } failed:^(NSError *error) {
        SHuiMBHidleYes;
        SHuiMBhudTextTimeStr(@"网络错误请重试！");
    }];
    
    
}


-(void)deledateOrderRequestFor:(NSString *)orderStr{
    
    NSDictionary * dic = @{@"user_id":USER_DEFAULTGet(@"user_id"),
                           @"token":USER_DEFAULTGet(@"token"),
                           @"order_id":orderStr};
    SHuiMBhubNoTimeLoding;
    [PostNetWorking postNetWorkingStr:RequestUrlStr(deledate_order_api) andparameters:dic Success:^(id responseObject) {
        SHuiMBHidleYes;
        if (codeSucess) {
            
            SHuiMBhudTextTimeStr(@"删除成功");
            _page = 1;
            [self getMyOrderListData];
        }else {
            
            SHuiMBhudTextTimeStr(responseObject[@"mark"]);
        }
        
    } failed:^(NSError *error) {
        SHuiMBHidleYes;
        SHuiMBhudTextNetError;
    }];
    
}


-(void)getOrderDetailsRequestFor:(NSString *)orderStr{
    
    NSDictionary * dic = @{@"user_id":USER_DEFAULTGet(@"user_id"),
                           @"token":USER_DEFAULTGet(@"token"),
                           @"order_id":orderStr};
    SHuiMBhubNoTimeLoding;
    [PostNetWorking postNetWorkingStr:RequestUrlStr(details_order_api) andparameters:dic Success:^(id responseObject) {
        SHuiMBHidleYes;
        if (codeSucess) {
            OrderDetailsViewController * details =[[OrderDetailsViewController alloc]init];
            details.dataDic = responseObject[@"datas"];
            [self.navigationController pushViewController:details animated:YES];
        }else {
            
            SHuiMBhudTextTimeStr(responseObject[@"mark"]);
        }
    } failed:^(NSError *error) {
        SHuiMBHidleYes;
        SHuiMBhudTextNetError;
    }];
    
}


/**
 *  封装边框按钮
 */
-(void)creatBoardBtnFrame:(CGRect)rec andTitleSte:(NSString *)title andSEL:(SEL)Click andBtnTag:
(NSInteger)tag onView:(UIView *)view {
    
    UIButton * deleBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    deleBtn.frame = rec;
    deleBtn.backgroundColor =[UIColor whiteColor];
    [deleBtn setTitle:title forState:UIControlStateNormal];
    [deleBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    deleBtn.layer.cornerRadius =15.f;
    deleBtn.layer.masksToBounds =YES;
    deleBtn.layer.borderWidth = 0.5f;
    deleBtn.layer.borderColor =[UIColor blackColor].CGColor;
    deleBtn.tag = tag;
    deleBtn.titleLabel.font = [UIFont systemFontOfSize:13];
    [deleBtn addTarget:self action:Click forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:deleBtn];
    
}



-(void)creatRedBtnFrame:(CGRect)rec andTitleStr:(NSString *)title andSel:(SEL)click andBtnTag:(NSInteger )tag onView:(UIView *)view {
    
    
    UIButton * btn =[UIButton buttonWithType:UIButtonTypeSystem];
    btn.frame = rec;
    btn.backgroundColor =[UIColor whiteColor];
    [btn setTitle:title forState:UIControlStateNormal];
    [btn setTitleColor:NavBackColor forState:UIControlStateNormal];
    btn.layer.cornerRadius =15.f;
    btn.layer.masksToBounds =YES;
    btn.titleLabel.font = [UIFont systemFontOfSize:13];
    btn.layer.borderWidth = 0.5f;
    btn.tag = tag ;
    btn.layer.borderColor = NavBackColor.CGColor;
    [btn addTarget:self action:click forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:btn];
    
}


@end
